import { Sortable, MultiDrag } from 'sortablejs';

Sortable.mount(new MultiDrag());
const tableDrag = {
  bind(el, binding) {
    const { value, arg } = binding;
    if (!el) {
      return;
    }
    const { elementSeletor, onEnd, ...config } = arg || {};
    const bindEls = elementSeletor ? el.querySelector(elementSeletor) : el;
    el.sortable = Sortable.create(bindEls, {
      multiDrag: true, // Enable multi-drag
      selectedClass: 'mselected', // The class applied to the selected items
      fallbackTolerance: 3, // So that we can select items on mobile
      animation: 150,
      ghostClass: 'blue-background-class',
      ...config,
      onEnd: (evt) => {
        let cloneValue = null;
        if (Array.isArray(value)) {
          const { oldIndex, newIndex } = evt;
          cloneValue = structuredClone(value);
          value.splice(newIndex, 0, ...value.splice(oldIndex, 1));
        }

        onEnd && onEnd(evt, cloneValue, value);
      },
      onMove(e) {
        // return e.related.className.indexOf('filtered') === -1;
      }
    });
    el.tableData = value;
  },

  update(el, { value }) {
    el.tableData = value;
  },

  unbind: function (el) {
    el.sortable.destroy();
    el.sortable = null;
  }
};

export default tableDrag;
